package site.shenjie.eureka.ribbon.feign.config;

import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.HttpClientConfig;
import com.aliyuncs.http.clients.ApacheHttpClient;
import feign.Client;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 沈杰
 * 2020-7-27 10:52:10
 * 配置类：Apache HttpClient配置类
 * 其通过 @ConditionalOnProperty 中的值来决定启用哪种客户端（ApacheHttpClient 和 OkHttp），
 * 其中@ConditionalOnClass 表示对应的类在 classpath 目录下存在时，才会去解析对应的配置文件。
 */
@Configuration
@ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
public class HttpClientFeignConfiguration {
    @Autowired(required = false)
    private HttpClient httpClient;

    @Bean
    @ConditionalOnMissingBean(Client.class)
    public ApacheHttpClient feignClient() throws ClientException {
        if (this.httpClient != null)
            return new ApacheHttpClient((HttpClientConfig) this.httpClient);
        return new ApacheHttpClient(new HttpClientConfig());
    }
}
